package main

import (
	"encoding/csv"
	"fmt"
	"os"
	"path/filepath"
	"text/template"

	"enzyme-backend/core/models"
)

// 生成规则代码
func generateRules() error {
	// 读取CSV文件
	file, err := os.Open("data/rules.csv")
	if err != nil {
		return fmt.Errorf("读取规则文件失败: %w", err)
	}
	defer file.Close()

	// 解析CSV
	reader := csv.NewReader(file)
	records, err := reader.ReadAll()
	if err != nil {
		return fmt.Errorf("解析CSV失败: %w", err)
	}

	// 跳过标题行，解析规则
	var rules []models.RuleConfig
	for i, record := range records {
		if i == 0 || len(record) < 3 {
			continue
		}
		rule := models.RuleConfig{
			Type:    record[0],
			Keyword: record[1],
			Group:   record[2],
		}
		rules = append(rules, rule)
	}

	// 生成代码
	tmpl := template.Must(template.New("rules").Parse(`// Code generated by go generate; DO NOT EDIT.
package generated

import (
	"enzyme-backend/core/models"
)

// ValidRules 有效的规则列表
var ValidRules = []models.RuleConfig{
{{range .}}	{ Type: "{{.Type}}", Keyword: "{{.Keyword}}", Group: "{{.Group}}", },
{{end}}}
`))

	// 确保目录存在
	outDir := "core/generated"
	if err := os.MkdirAll(outDir, 0755); err != nil {
		return fmt.Errorf("创建目录失败: %w", err)
	}

	// 写入生成的代码
	f, err := os.Create(filepath.Join(outDir, "valid_rules_gen.go"))
	if err != nil {
		return fmt.Errorf("创建文件失败: %w", err)
	}
	defer f.Close()

	if err := tmpl.Execute(f, rules); err != nil {
		return fmt.Errorf("生成代码失败: %w", err)
	}

	return nil
}

func main() {
	if err := generateRules(); err != nil {
		fmt.Fprintf(os.Stderr, "生成规则失败: %v\n", err)
		os.Exit(1)
	}
}
